package com.yuteng.security.config.handler;

import com.alibaba.fastjson.JSON;

import com.yuteng.security.config.JwtTokenUtil;
import com.yuteng.security.config.RedisUtils;
import com.yuteng.security.entity.Result;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {

    @Resource
    JwtTokenUtil jwtTokenUtil;
    @Resource
    RedisUtils redisUtils;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        final String realToken = jwtTokenUtil.generateToken(authentication.getName());
        List list=new ArrayList();
        list.add(realToken);
        /*
        把token放到redis中,key是username，value是token
         */
        if (redisUtils.get(authentication.getName())==null){           //半个小时
            redisUtils.set(authentication.getName(),realToken,30*60L, TimeUnit.SECONDS);
            //将生成的authentication放入容器中，生成安全的上下文
            SecurityContextHolder.getContext().setAuthentication(authentication);
            httpServletResponse.setContentType("text/json;charset=utf-8");
            httpServletResponse.getWriter().write(JSON.toJSONString(new Result<String>(true,5000,"登录成功",list)));
        }else {
            redisUtils.remove(authentication.getName());
            redisUtils.set(authentication.getName(),realToken,30*60L, TimeUnit.SECONDS);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            httpServletResponse.setContentType("text/json;charset=utf-8");
            httpServletResponse.getWriter().write(JSON.toJSONString(new Result<String>(true,5000,"登录刷新成功",list)));
        }
    }

}
